"""
认证相关 API
严格按照原 Flask 项目的接口实现，保持 100% 兼容性
"""
from fastapi import APIRouter, Depends

from sqlalchemy.ext.asyncio import AsyncSession

from  core.database import get_db
from  core.security import create_access_token
from  schemas.doctor import DoctorCreate, DoctorLogin, DoctorLoginResponse
from  schemas.patient import PatientWxLogin, PatientLoginResponse
from  schemas.hospital import ValidateCodeRequest
from  crud import doctor as crud_doctor
from  crud import patient as crud_patient
from  crud import hospital as crud_hospital

router = APIRouter()


@router.post("/register")
async def register(
    doctor_in: DoctorCreate,
    db: AsyncSession = Depends(get_db)
):
    """
    医生注册
    原接口: POST /auth/register
    """
    try:
        # 检查手机号是否已注册
        existing_doctor = await crud_doctor.get_by_phone(db, phone=doctor_in.phone)
        if existing_doctor:
            return {
                "message": "该手机号已注册",
                "code": 1
            }
        
        # 创建医生
        doctor = await crud_doctor.create(db, obj_in=doctor_in)
        await db.commit()
        
        return {
            "message": "注册成功",
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.post("/login")
async def login(
    login_data: DoctorLogin,
    db: AsyncSession = Depends(get_db)
):
    """
    医生登录
    原接口: POST /auth/login
    """
    try:
        phone = login_data.phone
        password = login_data.password
        
        if not phone or not password:
            return {
                "message": "手机号和密码不能为空",
                "code": 1
            }
        
        # 验证登录
        doctor = await crud_doctor.authenticate(
            db,
            phone=phone,
            password=password
        )
        
        if not doctor:
            return {
                "message": "账号或密码错误",
                "code": 1
            }
        
        if doctor.status != 1:
            return {
                "message": "账号或密码错误",
                "code": 1
            }
        
        # 生成 token（添加额外声明，与原项目一致）
        from datetime import timedelta
        access_token = create_access_token(
            data={
                "sub": str(doctor.id),  # ✅ JWT 标准要求 sub 必须是字符串
                "name": doctor.name,
                "phone": doctor.phone
            },
            expires_delta=timedelta(days=7)
        )
        
        # 使用 Schema 转换为原 Flask 格式
        login_response_data = DoctorLoginResponse.from_doctor(doctor, access_token)
        
        return {
            "message": "登录成功",
            "data": login_response_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.post("/wx-patient-login")
async def patient_login(
    login_data: PatientWxLogin,
    db: AsyncSession = Depends(get_db)
):
    """
    患者微信登录
    原接口: POST /auth/wx-patient-login
    """
    try:
        id_card = login_data.id_card
        phone = login_data.phone
        
        if not id_card or not phone:
            return {
                "message": "身份证号和手机号不能为空",
                "code": 1
            }
        
        # 查询患者
        patient = await crud_patient.get_by_id_card_and_phone(
            db,
            id_card=id_card,
            phone=phone
        )
        
        if not patient:
            return {
                "message": "未找到患者，请检查身份证号码和手机号是否正确",
                "code": 1
            }
        
        # 使用 Schema 转换为原 Flask 格式
        patient_data = PatientLoginResponse.from_patient(patient)
        
        return {
            "message": "登录成功",
            "data": patient_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.post("/validate-code")
async def validate_code(
    validate_data: ValidateCodeRequest,
    db: AsyncSession = Depends(get_db)
):
    """
    验证医院邀请码
    原接口: POST /auth/validate-code
    """
    try:
        hospital_name = validate_data.hospital_name
        invite_code = validate_data.invite_code
        
        if not hospital_name or not invite_code:
            return {
                "message": "医院名称和邀请码不能为空",
                "code": 1
            }
        
        # 查询医院，检查名称和邀请码是否匹配
        hospital = await crud_hospital.validate_code(
            db,
            hospital_name=hospital_name,
            invite_code=invite_code
        )
        
        print("hospital", hospital_name, invite_code, hospital)
        
        if not hospital:
            return {
                "message": "医院名称与邀请码不匹配",
                "code": 1
            }
        
        return {
            "message": "验证成功",
            "data": [],
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


